import * as vscode from 'vscode'
import { getLogger } from './init'
import { SidebarWebivewProvider } from './sidebar'
import { decodeDiffDocUri, DiffDocProvider } from './sidebar/diffDocProvider'
import { debounce } from './util/debounce'

export function activate(context: vscode.ExtensionContext) {
  const floders = vscode.workspace.workspaceFolders
  if (!floders || floders.length === 0) {
    return
  }
  const logger = getLogger()

  const folder = floders[0]

  logger.log(`folder.uri.fsPath=${folder.uri.fsPath}`)

  const sidebarWebivewProvider = new SidebarWebivewProvider(context.extensionUri, folder.uri)
  context.subscriptions.push(
    vscode.window.registerWebviewViewProvider('reviewMycode.sidebar', sidebarWebivewProvider)
  )

  context.subscriptions.push(
    vscode.workspace.registerTextDocumentContentProvider(
      DiffDocProvider.scheme,
      new DiffDocProvider(sidebarWebivewProvider.git)
    )
  )

  context.subscriptions.push(
    vscode.commands.registerCommand('reviewMycode.refreshBranchs', () => {
      sidebarWebivewProvider.queryAndPostBranches()
    })
  )
  context.subscriptions.push(
    vscode.commands.registerCommand('reviewMycode.clearAll', () => {
      sidebarWebivewProvider.clearAll()
    })
  )
  context.subscriptions.push(
    vscode.commands.registerCommand('reviewMycode.openFile', async (uri: vscode.Uri) => {
      if (uri && typeof uri === 'object' && uri.scheme === DiffDocProvider.scheme) {
        const gitRoot = await sidebarWebivewProvider.getGitRoot()
        const request = decodeDiffDocUri(uri)
        vscode.commands.executeCommand(
          'vscode.open',
          vscode.Uri.joinPath(gitRoot, request.filePath),
          { selection: vscode.window.activeTextEditor?.selection, preview: true }
        )
      }
    })
  )
  context.subscriptions.push(
    vscode.commands.registerCommand('reviewMycode.copyFilePath', (uri: vscode.Uri) => {
      if (uri && typeof uri === 'object' && uri.scheme === DiffDocProvider.scheme) {
        const request = decodeDiffDocUri(uri)
        vscode.env.clipboard.writeText(request.filePath)
      }
    })
  )
  context.subscriptions.push(
    vscode.window.onDidChangeVisibleTextEditors(
      debounce((editors: readonly vscode.TextEditor[]) => {
        sidebarWebivewProvider.queryAndPostActiveFilePath(editors)
      }, 50)
    )
  )
}

export function deactivate() {}
